import { getListApi, addUserApi, deleteUserApi, updateUserApi, uploadApi, userLoginApi, getUsersInfoApi } from '../api/audit/index'
import { UserTokenCookie } from '../utils/cookie'
export const state = () => ({
    tableData: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    roles: [],
    userInfo: {}
})

export const mutations = {
    SET_DATA(state, val) {
        state.tableData = val.data
        state.total = val.total
    },
    CURRENTPAGE(state, val) {
        state.currentPage = val
    },
    PAGESIZE(state, val) {
        state.pageSize = val
    },
    SET_ROLES(state, val) {
        state.roles = val
    },
    SET_USERINFO(state, val) {
        state.userInfo = val
    }
}

export const actions = {
    async getList({ commit, state }, query) {
        const r = await getListApi({ currentPage: state.currentPage - 1, pageSize: state.pageSize, query })
        commit('SET_DATA', { data: r.data, total: r.total })
    },

    async addUser({ dispatch }, data) {
        await addUserApi(data)
        dispatch('getList')
    },

    async deleteUser({ dispatch }, data) {
        await deleteUserApi(data)
        dispatch('getList')
    },

    async updateUser({ dispatch }, data) {
        await updateUserApi(data)
        dispatch('getList')
    },

    async upload(context, data) {
        await uploadApi(data)
    },

    async userLogin(context, form) {
        const { data } = await userLoginApi(form)
        const token = data.token
        UserTokenCookie.setToken(token)
    },

    async getUserInfo({ commit }, token) {
        const { data } = await getUsersInfoApi({ token })
        const { roles } = data
        const obj = data
        commit('SET_ROLES', roles.split(','))
        commit('SET_USERINFO', obj)
    },

    async logout({ commit }) {
        commit('SET_ROLES',[])
        commit('SET_USERINFO',{})
        UserTokenCookie.removeToken()
    }
}

export const getters = {}